import React, {useRef, useState, useEffect} from 'react';
import {
  Text,
  View,
  ImageBackground,
  Animated,
  default as Easing,
  StyleSheet,
  PermissionsAndroid,
} from 'react-native';
import {RNCamera} from 'react-native-camera';
import {useIsFocused} from '@react-navigation/core';
import LightIcon from '../assets/icon/light.svg';

const ScanScreen = ({navigation}) => {
  const isFocused = useIsFocused();
  const scanLine = useRef(new Animated.Value(10)).current;
  const [flashMode, setFlashMode] = useState(RNCamera.Constants.FlashMode.off);
  useEffect(() => {
    requestCameraPermission();
    startScanLine();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  //请求权限的方法
  const requestCameraPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.CAMERA,
        {
          title: '申请摄像头权限',
          message: '扫描二维码需要开启相机权限',
          buttonNeutral: '等会再问我',
          buttonNegative: '不行',
          buttonPositive: '好吧',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log('现在你获得摄像头权限了');
      } else {
        console.log('用户没有允许相机权限');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  const startScanLine = () => {
    Animated.sequence([
      Animated.timing(scanLine, {
        toValue: 195,
        duration: 1500,
        easing: Easing.linear,
        useNativeDriver: false,
      }),
      Animated.timing(scanLine, {
        toValue: 5,
        duration: 1500,
        easing: Easing.linear,
        useNativeDriver: false,
      }),
    ]).start(() => startScanLine());
  };

  const onBarCodeRead = ({data}) => {
    console.log(data);
    navigation.navigate('ScanResultScreen', {
      data: data,
    });
  };

  if (!isFocused) {
    return <View style={styles.container} />;
  }
  return (
    <View style={styles.container}>
      <RNCamera
        autoFocus={RNCamera.Constants.AutoFocus.on} /*自动对焦*/
        style={[styles.preview]}
        type={RNCamera.Constants.Type.back} /*切换前后摄像头 front前back后*/
        flashMode={flashMode} /*相机闪光模式*/
        barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
        captureAudio={false}
        onBarCodeRead={onBarCodeRead}>
        {/* 顶部阴影区域 */}
        <View style={styles.top} />
        {/* 中间部分 */}
        <View style={styles.main}>
          {/* 中部左侧阴影区域 */}
          <View style={styles.mainLeft} />
          {/* 扫码区域 */}
          <ImageBackground
            source={require('../assets/image/qrcode_bg.png')}
            style={styles.scanContainer}>
            {/* 扫描条动画 */}
            <Animated.View
              style={[styles.scanLine, {transform: [{translateY: scanLine}]}]}
            />
          </ImageBackground>
          {/* 中部右侧阴影区域 */}
          <View style={styles.mainRight} />
        </View>
        {/* 底部阴影区域 */}
        <View style={styles.bottom}>
          <Text style={styles.rectangleText}>
            将二维码放入框内，即可自动扫描
          </Text>
          <LightIcon
            with={40}
            height={40}
            fill={
              flashMode === RNCamera.Constants.FlashMode.torch
                ? '#ffff00'
                : '#fff'
            }
            onPress={() => {
              if (flashMode === RNCamera.Constants.FlashMode.torch) {
                setFlashMode(RNCamera.Constants.FlashMode.off);
              } else {
                setFlashMode(RNCamera.Constants.FlashMode.torch);
              }
            }}
          />
        </View>
      </RNCamera>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  preview: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  top: {
    flex: 1,
    width: '100%',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  main: {
    flexDirection: 'row',
    height: 200,
  },
  mainLeft: {
    backgroundColor: 'rgba(0,0,0,0.5)',
    height: 200,
    flex: 1,
  },
  scanContainer: {
    width: 200,
    height: 200,
    alignItems: 'center',
  },
  mainRight: {
    backgroundColor: 'rgba(0,0,0,0.5)',
    height: 200,
    flex: 1,
  },
  bottom: {
    flex: 1,
    width: '100%',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    alignItems: 'center',
  },
  scanLine: {
    width: 190,
    height: 2,
    backgroundColor: '#02c26f',
  },
  rectangleText: {
    flex: 0,
    color: '#fff',
    marginTop: 10,
    marginBottom: 20,
  },
});

export default ScanScreen;
